<template>
  <div class="preview-md">
    <v-collapse v-model="collapse">
      <v-collapse-item :value="1">
        <div slot="header" class="preview-md-header">
          <div class="preview-md-header-inner">
            <div
              class="left"
              :title="title || '未知文档'"
              @click.stop="showPreview(url)"
            >
              {{ title || "未知文档" }}
            </div>
          </div>
          <v-icon
            :name="
              collapse.length ? 'arrow_up_small_line' : 'arrow_down_small_line'
            "
            size="12"
            style="color: var(--color-text-caption)"
            remote
          />
        </div>
        <div slot="content" class="preview-md__main">
          <div class="main-content" v-if="!isError">
            <div v-for="(item, index) in list" :key="index">
              <div class="section">
                <div class="title" v-if="type === 2">
                  {{ `#文档片段${addLeadingZero(index + 1)}` }}
                </div>
                <VueMarkdown
                  v-if="type === 2"
                  :source="xssHandlerProcess(replaceLinks(item.fileContent))"
                  :anchorAttributes="{ target: '_blank' }"
                  :linkify="false"
                  table-class="table-style"
                  :emoji="false"
                />
                <div v-else>
                  <div class="content-qa-title">问题：</div>
                  <div>{{ item.question }}</div>
                  <div class="content-qa-title" style="margin-top: 20px">
                    答案：
                  </div>
                  <div>
                    <VueMarkdown
                      :source="
                        escapeMarkdownStars(
                          escapeSingleTilde(xssHandlerProcess(item.answer))
                        )
                      "
                      :anchorAttributes="{ target: '_blank' }"
                      :linkify="false"
                      table-class="table-style"
                      :emoji="false"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="main-content error" v-else>
            <!-- <img class="error-img" src="@/assets/img/docPreviewError.png" /> -->
            <div class="error-desc">文档读取失败</div>
          </div>
        </div>
      </v-collapse-item>
    </v-collapse>
  </div>
</template>

<script>
import VueMarkdown from "vue-markdown";
import {
  getQueryVariable,
  getShareCode,
  escapeSingleTilde,
  escapeMarkdownStars,
  getUserCategory,
} from "@/utils/util";
import { ChatUserCategory } from "@/constants";

export default {
  name: "MdPreview",
  components: {
    VueMarkdown,
  },
  props: {
    referIds: {
      type: Array,
    },
    title: {
      required: false,
      type: String,
    },
    type: {
      required: false,
      type: Number,
      default: 2,
    },
    url: {
      required: false,
      type: String,
    },
    ifOpen: {
      required: false,
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      confidence: undefined,
      fileName: "",
      fileContent: "",
      isError: false,
      collapse: [],
      currentFeedbackStatus: "", // 正确-'good' 错误 - 'bad'
      currentFeedbackFinished: false,
      feedBackLoading: false,
      answer: "",
      question: "",
      list: [],
    };
  },
  computed: {
    // feedbackDisabled () {
    //     return (this.currentFeedbackFinished && !!this.currentFeedbackStatus) || this.feedBackLoading;
    // },
    relativityAsPercentage() {
      if (isNaN(this.confidence)) {
        return "-";
      }
      return `${(this.confidence * 100).toFixed(2)}%`;
    },
  },
  created() {
    this.getDocInfo();
  },
  watch: {
    fileContent(val) {
      if (val) {
        if (this.ifOpen) {
          setTimeout(() => {
            this.collapse = [1];
          }, 200);
        }
      }
    },
    question(val) {
      if (val) {
        if (this.ifOpen) {
          setTimeout(() => {
            this.collapse = [1];
          }, 200);
        }
      }
    },
    referIds(val) {
      this.getDocInfo();
    },
  },
  methods: {
    escapeSingleTilde,
    escapeMarkdownStars,
    showPreview(url) {
      const sharecode = getShareCode();
      const botBizId =
        window.localStorage.getItem(`bot_biz_id_im_${sharecode}`) ||
        getQueryVariable("bot_biz_id");
      // console.log(233333777, url, this.referId, botBizId);
      console.log(
        "final url ===== ",
        getUserCategory(),
        url + "&botBizId=" + botBizId
      );
      // console.log('open preview url---->', url);
      // let openurl = `${window.location.origin}/preview?id=${url}`;
      // https://tde.xiaowei.cloud.tencent.com/preview?id=1740367443300044800&botBizId=1734932415645614080
      if (getUserCategory() === ChatUserCategory.PHONE_NUMBER) {
        window.open(url);
      } else {
        const currentPageUrl = window.location.href;
        const cleanGivenLink = url.replace(new RegExp("^https?:\\/\\/"), "");
        const cleanCurrentPageUrl = currentPageUrl.replace(
          new RegExp("^https?:\\/\\/"),
          ""
        );
        if (cleanGivenLink === cleanCurrentPageUrl) {
          window.open(url + "&botBizId=" + botBizId);
        } else {
          window.open(url);
        }
      }
    },
    routerPrefix() {
      let prefix = "";
      let commonParams = "";
      if (window.__POWERED_BY_QIANKUN__) {
        prefix = "/lke";
        commonParams = ""; // '/:product_id/:user_id';
      }
      return window.__POWERED_BY_QIANKUN__ ? `${prefix}${commonParams}` : "";
    },
    matchImageLinks(text) {
      const regex = new RegExp("!\\[([^\\]]+)\\]\\(([^)]+)\\)", "g");
      const matches = [];
      let match;
      while ((match = regex.exec(text)) !== null) {
        matches.push(match[0]);
      }
      return matches;
    },

    replaceLinks(text) {
      if (!text) return text;
      text = text.replace(new RegExp("\\\\([*_()])", "g"), "$1");
      // 先把里面的图片保留
      const matchImgs = this.matchImageLinks(text);
      matchImgs.forEach((i, index) => {
        text = text.replace(i, `IMG_URL${index}`);
      });
      const from = getQueryVariable("from");
      const replaceUrl = from
        ? ""
        : `${window.location.protocol}//${window.location.host}/${this.routerPrefix}/#/link-info/redirect?target=`;
      const regex = new RegExp(
        '(\\[([^\\]]+)\\]\\((https?:\\/\\/(?!oaqbot\\.qidian\\.qq\\.com)[^\\s)]+)\\))|(<a\\s+[^>]*href="((?!oaqbot\\.qidian\\.qq\\.com)[^"]+)"[^>]*>(.*?)<\\/a>)',
        "gi"
      );
      text = text.replace(regex, (match, p1, p2, p3, p4, p5, p6) => {
        if (p1 && p2) {
          return `[${p2}](${replaceUrl}${p3})`;
        } else if (p5 && !p5.startsWith("#")) {
          return `<a href="${replaceUrl}${p5}">${p6}</a>`;
        } else {
          return match;
        }
      });
      matchImgs.forEach((i, index) => {
        text = text.replace(`IMG_URL${index}`, i);
      });
      return text;
    },

    async getDocInfo() {
      try {
        const botBizId =
          window.localStorage.getItem("bot_biz_id_im") ||
          getQueryVariable("bot_biz_id");

        const res = await this.$ajax.post("DescribeRefer", {
          ReferBizIds: this.referIds,
          BotBizId: botBizId,
        });

        const { list } = res;
        for (let i = 0; i < list.length; i++) {
          let item = list[i];
          if (this.type === 1) {
            // do nothing
          } else {
            if (item.doc_type === 2) {
              // eslint-disable-next-line no-useless-escape
              item.fileContent = item.page_content.replace(
                new RegExp("!\\[(.*?)\\]\\((.*?)\\)", "g"),
                '<img src="$2" alt="$1">'
              );
              // 找出高亮的文本
              item.highlights &&
                item.highlights.forEach((i) => {
                  item.fileContent = item.fileContent.replaceAll(
                    i.text,
                    `<span class="highlight-text-bg">${i.text}</span>`
                  );
                });
              if (item.mark === 0) {
                item.currentFeedbackFinished = false;
              } else {
                item.currentFeedbackFinished = true;
                if (item.mark === 1) {
                  item.currentFeedbackStatus = "good";
                }
                if (item.mark === 2) {
                  item.currentFeedbackStatus = "bad";
                }
              }
            }
          }
        }
        this.list = list;
      } catch (error) {
        console.log(error);
      }
    },
    addLeadingZero(number, length = 2) {
      return String(number).padStart(length, "0");
    },
    // 反馈引用文档是否正确
    // async handleReferAudit (opt) {
    //     if (this.currentFeedbackStatus) {
    //         return this.$message.warning('已反馈成功，无需重复反馈');
    //     };
    //     this.currentFeedbackStatus = opt ? 'good' : 'bad';
    //     const markPayload = opt ? 1 : 2;
    //     try {
    //         this.feedBackLoading = true;
    //         await this.$ajax.post('MarkRefer', {
    //             ReferBizId: this.referId,
    //             mark: markPayload
    //         });
    //         this.$message.success('反馈成功');
    //         this.currentFeedbackFinished = true;
    //     } catch (error) {
    //         this.currentFeedbackStatus = '';
    //         console.log(error);
    //         this.$message.error('反馈失败，请稍后重试');
    //     } finally {
    //         this.feedBackLoading = false;
    //     }
    // }
  },
};
</script>

<style lang="less">
.preview-md {
  //   width: 100%;
  //   height: 100%;
  //   overflow-x: hidden;
  //   overflow-y: scroll;
  //   margin-top: 8px;
  .v-collapse {
    background-color: var(--color-bg-1);
    border-radius: var(--radius-large);
  }

  .v-collapse-item {
    border: 1px solid var(--color-divider-normal);
    border-radius: 3px;
  }

  .v-collapse-item.isShow {
    .v-collapse-item__header {
      color: var(--color-text-primary);
      background: inherit;
    }
    &.isShow .v-collapse-item__header {
      border-bottom: 1px solid var(--color-divider-normal);
    }
  }

  .preview-md-header {
    display: flex;
    justify-content: space-between;
    width: 100%;
    height: 100%;
    font-size: 16px;
    font-weight: 500;
    align-items: center;
    .preview-md-header-inner {
      display: flex;
      justify-content: flex-start;
      width: calc(100% - 12px);
      & > div {
        display: inline-block;
        text-align: left;
      }
      .left {
        // max-width: 340px;
        width: 100%;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  &__main {
    .main-content {
      word-break: break-all;
      word-wrap: break-word;
      display: flex;
      flex-direction: column;
      align-items: flex-start;
      flex: 0 0 604px;
      height: 604px;
      padding: 16px;
      overflow-x: auto;
      overflow-y: auto;
      background: var(--color-bg-1);
      border: 1px solid var(--divider-color-divider-normal);

      .section {
        margin-bottom: 20px;
        padding: 12px;
        border-radius: var(--radius-large);
        background: var(--color-bg-2);
        box-shadow: var(--shadow-small-light-x-1) var(--shadow-small-light-y-1)
            var(--shadow-large-light-blur-1) var(--shadow-small-light-spread-1)
            var(--shadow-small-light-color-1),
          var(--shadow-small-light-x-2) var(--shadow-small-light-y-2)
            var(--shadow-small-light-blur-2) var(--shadow-small-light-spread-2)
            var(--shadow-small-light-color-2),
          var(--shadow-small-light-x-3) var(--shadow-small-light-y-3)
            var(--shadow-small-light-blur-3) var(--shadow-small-light-spread-3)
            var(--shadow-small-light-color-3);
        .title {
          display: inline-block;
          border-radius: var(--radius-normal);
          border: 1px solid var(--color-gray-2);
          background: var(--color-gray-0);
          color: var(--color-gray-4);
          font-family: var(--font-family-normal);
          font-size: 12px;
          font-weight: 500;
          line-height: 16px;
        }

        img {
          width: 200px;
          height: 200px;
        }
      }

      .content-qa-title {
        color: rgba(0, 11, 52, 0.41);
        font-family: PingFang SC;
        font-size: 14px;
        font-style: normal;
        font-weight: 400;
        line-height: 20px; /* 142.857% */
      }

      /deep/ p {
        /* 预览时，p元素上方margin会导致回答左右元素上方不对齐 */
        margin: 0;
      }
      .table {
        /* 滚动条Track */
        ::-webkit-scrollbar-track {
          background: transparent;
        }

        /* Handle */
        ::-webkit-scrollbar-thumb {
          border-radius: 10px;
          background: rgba(17, 32, 70, 0.13);
        }
      }
      /deep/ img {
        max-width: 100%;
      }
      p {
        word-break: break-all;
        word-wrap: break-word;
      }
      code {
        white-space: break-spaces;
      }
      table {
        // display: inline-block;
        // white-space: nowrap;
        // max-width: 100%;
        // overflow: scroll;
        // background: white;
        // border-bottom: 1px solid rgba(18, 42, 79, 0.08);
        // border-right: 1px solid rgba(18, 42, 79, 0.08);
        // border-spacing: 0;
        // border-collapse: collapse;
        display: inline-block;
        overflow-x: scroll;
        background: white;
        border-spacing: 0;
        border-collapse: collapse;
        border-bottom: 1px solid rgba(18, 42, 79, 0.08);
        border-right: 1px solid rgba(18, 42, 79, 0.08);
        max-width: 100%;
        th {
          background: #eaecef;
          color: rgba(1, 11, 50, 0.41);
          // padding: 12px;
          // font-weight: 400;
          // background: #eaecef;
        }
        td,
        th {
          border-left: 1px solid rgba(18, 42, 79, 0.08);
          border-top: 1px solid rgba(18, 42, 79, 0.08);
        }
        td {
          padding: 8px 12px;
          min-width: 20px;
        }
      }
      .table-style {
        display: inline-block;
        white-space: nowrap;
        max-width: 100%;
        overflow: scroll;
        background: white;
        border-bottom: 1px solid rgba(18, 42, 79, 0.08);
        border-right: 1px solid rgba(18, 42, 79, 0.08);
        border-spacing: 0;
        border-collapse: collapse;
        th {
          color: rgba(1, 11, 50, 0.41);
          padding: 12px;
          font-weight: 400;
          background: #eaecef;
        }
        td,
        th {
          border-left: 1px solid rgba(18, 42, 79, 0.08);
          border-top: 1px solid rgba(18, 42, 79, 0.08);
        }
        td {
          padding: 8px 4px;
          min-width: 45px;
          overflow-wrap: break-word;
          white-space: break-spaces;
        }
      }
    }
    .audit-feedback {
      display: flex;
      padding: 12px;
      justify-content: space-between;
      align-items: center;
      border-top: 1px solid var(--color-divider-normal);
      .tips {
        color: var(--color-text-caption);
      }
      .feedback {
        display: flex;
        justify-content: space-between;
        cursor: pointer;
        &.disabled {
          cursor: not-allowed;
        }

        .feedback-btn {
          display: flex;
          align-items: center;
          .icon {
            margin-right: 4px;
          }
        }

        .good {
          margin-right: 8px;
          color: var(--color-success-normal);
        }
        .bad {
          color: var(--color-error-normal);
        }
      }
    }

    .main-content.error {
      padding-top: 100px;
      align-items: center;

      .error-img {
        width: 200px;
        height: 200px;
      }
      .error-desc {
        margin-top: 12px;
        font-weight: 500;
        font-size: 16px;
        color: var(--color-text-primary);
      }
    }
  }
}
</style>
